package com.itsu.spbspider.service.impl;

import com.itsu.spbspider.entity.News;
import com.itsu.spbspider.mapper.NewsMapper;
import com.itsu.spbspider.service.OrmData;
import com.itsu.spbspider.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BaiduNewsOrmData implements OrmData {

    @Resource
    private NewsMapper newsMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void writeDataToDb(List<News> list) throws Exception {
        for (News news : list) {
            newsMapper.insert(news);
        }
    }

    @Override
    public void writeDataToDbTask(List<News> list) throws Exception {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        NewsMapper mapper = sqlSession.getMapper(NewsMapper.class);
        try {
            for (News news : list) {
                mapper.insertOne(news);
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }

    }
}
